package com.aliyun.tiangong.aspect;

import com.aliyun.tiangong.annotation.BeanValidate;
import com.aliyun.tiangong.exception.ParameterInValidException;
import com.aliyun.tiangong.util.BeanValidateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author xinghen
 * @ClassName: BeanValidateAspect
 * @Package: com.xinghen.common.core.aspect
 * @Description 方法入参校验切面类
 * @create 2018-04-11 15:52
 */
@Component
@Aspect
public class BeanValidateAspect {

    @Pointcut("@annotation(com.aliyun.tiangong.annotation.BeanValidate)")
    public void beanValidatePointcut() {
    }

    @Around("beanValidatePointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        BeanValidate annotation = signature.getMethod().getAnnotation(BeanValidate.class);
        if (Objects.nonNull(annotation) && args.length > 0) {
            Class<?> clazz = annotation.validateClass();
            Object needValidateArg = null;
            for (Object arg : args) {
                if (clazz.isAssignableFrom(arg.getClass())) {
                    needValidateArg = arg;
                    break;
                }
            }
            if (Objects.isNull(needValidateArg)) {
                throw new ParameterInValidException("BeanValidate需要配置校验参数类型");
            }
            BeanValidateUtil.validate(needValidateArg);
        }
        return joinPoint.proceed();
    }

}
